package cn.gxm.tools.migration.address;

import com.app.common.segmentwords.AnalyzerUtils;
import com.app.common.segmentwords.SplictByDictAnalyzer;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class DataLoader {
    private SplictByDictAnalyzer analyzer = new SplictByDictAnalyzer();
    private Connection conn;
    private PreparedStatement pstmt;
    private ResultSet rs;

    private String tableName;
    private String idName = "id";
    private String addressName = "address";

    public DataLoader(String tableName, String idName, String addressName) {
        this.tableName = tableName;
        this.idName = idName;
        this.addressName = addressName;
    }

    public void setConn(Connection conn) {
        this.conn = conn;
    }

    public void setAnalyzer(SplictByDictAnalyzer analyzer) {
        this.analyzer = analyzer;
    }

    /**
     * 从数据库加载地址数据。
     *
     * @param callback 数据加载的回调
     * @return 返回有效处理的记录条数
     * @throws SQLException
     */
    public int load(LoadCallback callback) throws SQLException {
        String sql = "SELECT " + idName + ", " + addressName + " FROM " + tableName;

        pstmt = conn.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY | ResultSet.CONCUR_READ_ONLY);
        rs = pstmt.executeQuery();

        int rows = 0;
        while (rs.next()) {
            long id = rs.getLong(idName);
            String address = rs.getString(addressName);

            if (address != null && !address.isEmpty()) {
                List<String> words = AnalyzerUtils.splitSentence(address, analyzer);

                if (!words.isEmpty()) {
                    rows++;
                    String address1 = words.get(0);
                    String address2 = "";
                    if (words.size() > 1) {
                        address2 = words.get(1);
                    }

                    callback.callback(id, address1, address2);
                }
            }
        }

        return rows;
    }

    public void finish() throws SQLException {
        rs.close();
        pstmt.close();
        conn.close();
    }
}
